package ltd.dujiabao.capability.adapter.driven.persistence.rulemng;

import java.util.concurrent.ExecutionException;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;

import ltd.dujiabao.capability.common.dto.ErrorCodes;
import ltd.dujiabao.capability.common.exception.BusinessException;
import ltd.dujiabao.capability.domain.capmng.cap.CapabilityIdentity;
import ltd.dujiabao.capability.domain.capmng.cap.CapabilityRepository;
import ltd.dujiabao.capability.domain.rulemng.RuleRepository;
import ltd.dujiabao.capability.domain.rulemng.Support;
import ltd.dujiabao.capability.domain.rulemng.SupportFactory;
import ltd.dujiabao.capability.domain.rulemng.SupportIdentity;

/**
 * @author : DuJiabao
 * @Project : ddd-capability
 * @Time : 2024/4/13 13:40
 * @Desc :
 */
@Component
public class SupportFactoryImpl implements SupportFactory {
    @Autowired
    private RuleRepository ruleRepository;
    @Autowired
    private CapabilityRepository capabilityRepository;
    @Autowired
    private RuleProperties ruleProperties;

    private Cache<SupportIdentity, Support> cache;

    @PostConstruct
    public void init() {
        cache = CacheBuilder.newBuilder()
                .maximumSize(ruleProperties.getSupport().getLruCacheSize())
                .build();
    }

    @Override
    public Support buildSupport(CapabilityIdentity capabilityIdentity, String funcName) {
        SupportIdentity supportIdentity = new SupportIdentity(capabilityIdentity, funcName);
        try {
            return cache.get(supportIdentity, () -> new Support(supportIdentity, ruleRepository, capabilityRepository));
        } catch (ExecutionException e) {
            throw new BusinessException(e, ErrorCodes.SYSTEM_INTERNAL_ERROR.getCode());
        }
    }
}
